package site.jlopen.controller.api;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import site.jlopen.assets.config.ThreadAuthUser;
import site.jlopen.domain.node.KusciaNode;
import site.jlopen.domain.node.KusciaNodeRoute;
import site.jlopen.domain.node.event.KusciaNodeEvent;
import site.jlopen.domain.node.event.KusciaNodeRouteEvent;
import site.jlopen.entity.BaseResponse;
import site.jlopen.entity.KusciaApiInfo;
import site.jlopen.kuscia.model.route.NodeRouteVo;
import site.jlopen.kuscia.service.noderoute.KusciaNodeRouteManager;
import site.jlopen.mapper.node.KusciaNodeMapper;
import site.jlopen.mapper.node.KusciaNodeRouteMapper;
import site.jlopen.utils.id.IdUtils;

@RestController
@RequestMapping(value="/api/route")
public class ApiRouteController {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private KusciaNodeMapper nodeMapper;
	@Autowired
	private KusciaNodeRouteMapper nodeRouteMapper;
	@Autowired
	private KusciaNodeRouteManager nodeRouteManager;
	
	@PostMapping(value = "/bind" )
	public BaseResponse<String> routeBind(String srcNodeCode, String destNodeCode, int bindType) {
		logger.info("节点路由绑定接口调用");
		KusciaNodeEvent srcNode = nodeMapper.selectByInfo(new KusciaNode().setNodeCode(srcNodeCode));
		if(null == srcNode) {
			return new BaseResponse<String>().error("节点编号"+srcNodeCode+"不存在");
		}
		KusciaNodeEvent dstNode = nodeMapper.selectByInfo(new KusciaNode().setNodeCode(destNodeCode));
		if(null == dstNode) {
			return new BaseResponse<String>().error("节点编号"+destNodeCode+"不存在");
		}
		KusciaNodeRouteEvent routrInfo = nodeRouteMapper.selectByInfo(
				new KusciaNodeRoute().setRouteSrcNode(srcNode.getNodeId()).setRouteDstNode(dstNode.getNodeId()));
		if(null != routrInfo) {
			return new BaseResponse<String>().error("已存在绑定，请自行刷新状态");
		}
		String routeName = null;
		KusciaApiInfo apiInfo = new KusciaApiInfo(srcNode.getNodeProtocol(), srcNode.getNodeGrpc()).ext(srcNode.getNodeToken(), srcNode.getNodeCert(), srcNode.getNodeKey(), srcNode.getNodeCa());
		if(bindType == 1) {
			NodeRouteVo routeVo = nodeRouteManager.queryDomainRoute(apiInfo, srcNode.getNodeCode(), dstNode.getNodeCode());
			if(null != routeVo) {
				return new BaseResponse<String>().error("合作节点已存在于kuscia，请使用关系绑定");
			}
			routeName = nodeRouteManager.createDomainRoute(apiInfo, srcNode.getNodeCode(), dstNode.getNodeCode(), dstNode.getNodeNet());
		}
		if(bindType == 1 && StringUtils.isBlank(routeName)) {
			return new BaseResponse<String>().error("绑定失败，kuscia未知错误");
		}
		routrInfo = new KusciaNodeRouteEvent();
		routrInfo.setRouteId(IdUtils.SnowFlakeId());
		routrInfo.setRouteSrcNode(srcNode.getNodeId());
		routrInfo.setRouteDstNode(dstNode.getNodeId());
		routrInfo.setRouteUserId(ThreadAuthUser.id());
		routrInfo.setRouteDeleted(0);
		routrInfo.setRouteStatus(1);
		routrInfo.setRouteCreate(new Date());
		int row = nodeRouteMapper.insertSelective(routrInfo);
		if(row > 0) {
			return new BaseResponse<String>().dbRes(row, "绑定成功");
		}
		return new BaseResponse<String>().error("节点绑定失败");
	}
	
	@PostMapping(value = "/unbind" )
	public BaseResponse<String> routeUnbind(String srcNodeCode, String destNodeCode) {
		logger.info("节点路由解绑接口调用");
		KusciaNodeEvent srcNode = nodeMapper.selectByInfo(new KusciaNode().setNodeCode(srcNodeCode));
		if(null == srcNode) {
			return new BaseResponse<String>().error("节点编号"+srcNodeCode+"不存在");
		}
		KusciaNodeEvent dstNode = nodeMapper.selectByInfo(new KusciaNode().setNodeCode(destNodeCode));
		if(null == dstNode) {
			return new BaseResponse<String>().error("节点编号"+destNodeCode+"不存在");
		}
		KusciaNodeRouteEvent routrInfo = nodeRouteMapper.selectByInfo(
				new KusciaNodeRoute().setRouteSrcNode(srcNode.getNodeId()).setRouteDstNode(dstNode.getNodeId()));
		if(null == routrInfo) {
			return new BaseResponse<String>().error("不存在绑定关系");
		}
		KusciaApiInfo apiInfo = new KusciaApiInfo(srcNode.getNodeProtocol(), srcNode.getNodeGrpc()).ext(srcNode.getNodeToken(), srcNode.getNodeCert(), srcNode.getNodeKey(), srcNode.getNodeCa());
		int row = nodeRouteMapper.deleteByKey(routrInfo.getRouteId());
		if(row > 0) {
			nodeRouteManager.deleteDomainRoute(apiInfo, srcNode.getNodeCode(), dstNode.getNodeCode());
		}
		return new BaseResponse<String>().dbRes(row, "解绑成功");
	}
	
	@PostMapping(value = "/refresh" )
	public BaseResponse<String> routeRefresh(String srcNodeCode, String destNodeCode) {
		logger.info("节点路由状态刷新接口调用");
		KusciaNodeEvent srcNode = nodeMapper.selectByInfo(new KusciaNode().setNodeCode(srcNodeCode));
		if(null == srcNode) {
			return new BaseResponse<String>().error("节点编号"+srcNodeCode+"不存在");
		}
		KusciaNodeEvent dstNode = nodeMapper.selectByInfo(new KusciaNode().setNodeCode(destNodeCode));
		if(null == dstNode) {
			return new BaseResponse<String>().error("节点编号"+destNodeCode+"不存在");
		}
		KusciaNodeRouteEvent routrInfo = nodeRouteMapper.selectByInfo(
				new KusciaNodeRoute().setRouteSrcNode(srcNode.getNodeId()).setRouteDstNode(dstNode.getNodeId()));
		if(null == routrInfo) {
			return new BaseResponse<String>().error("不存在绑定关系");
		}
		KusciaApiInfo apiInfo = new KusciaApiInfo(srcNode.getNodeProtocol(), srcNode.getNodeGrpc()).ext(srcNode.getNodeToken(), srcNode.getNodeCert(), srcNode.getNodeKey(), srcNode.getNodeCa());
		NodeRouteVo routeVo = nodeRouteManager.queryDomainRoute(apiInfo, srcNode.getNodeCode(), dstNode.getNodeCode());
		int status = 0;
		if(null == routeVo) {
			String routeName = nodeRouteManager.createDomainRoute(apiInfo, srcNode.getNodeCode(), dstNode.getNodeCode(), dstNode.getNodeNet());
			if(StringUtils.isBlank(routeName)) {
				status = 1;
			}
		} /*else if (routeVo.isSuccess() == false) {
			status = 1;
			}*/
		routrInfo.setRouteStatus(status);
		nodeRouteMapper.updateSelective(routrInfo);
		return new BaseResponse<String>().success("状态已刷新");
	}
	
	/*@PostMapping(value = "/exist" )
	public BaseResponse<String> routeExist() {
		logger.info("节点接口调用");
		return new BaseResponse<String>().success("成功");
	}*/
}